<template>
	<section id="data_list_warp">
		<section class="noList" v-show="list.length == 0"><van-loading color="black" /></section>
		<ul class="list_warp">
			<li class="list" v-for="(v,i) in list" @click="goKline(v.code,v.name)">
				<p class="name">{{v.name}}</p>
				<p class="price">{{v.price}}</p>
				<p class="gains" v-if="v.change>=0">
					<span class="bg bg_up">{{v.changePercentage}}</span>
				</p>
				<p class="gains" v-else>
					<span class="bg bg_down">{{v.changePercentage}}</span>
				</p>
			</li>
		</ul>
	</section>
</template>
<script>
	export default {
		data() {
			return {
				list: [],
				code: 'eth_usdt',
				name: '"ETH_USDT"',
				websocket: ''
			}
		},
		props: ['method'], //接受这个事件
		methods: {
			getData() {
				var _this = this;
				_this.$http.get(_this.$host.hang, {
					params: {
						type: 2
					}
				}).then(function(response) {
					if(response.data.code == "200") {
						_this.list = response.data.data;
					}
				}).catch(function(error) {});
			},
			WebSocketindex() {
				var _this = this;
				// 首先判断是否 支持 WebSocket
				if('WebSocket' in window) {
					_this.websocket = new WebSocket(_this.$websock);
				} else if('MozWebSocket' in window) {
					_this.websocket = new WebSocket(_this.$websock);
				} else {
					_this.websocket = new SockJS(_this.$websock);
				}
				// 打开时
				_this.websocket.onopen = function(evnt) {
					var msg = {
						type: "vb_okex"
					};
					// 发送消息
					_this.websocket.send(JSON.stringify(msg));
				};
				// 处理消息时
				_this.websocket.onmessage = function(evnt) {
					var datanum = JSON.parse(evnt.data);
					_this.list.forEach(function(i, v) {
						if(i.code == datanum.code) {
							_this.list[v].price = datanum.price;
							_this.list[v].changePercentage = datanum.changePercentage;
							_this.list[v].change = datanum.change;
						}
					})

				};
			},
			//接受传过来的控制函数
			goKline(v, n) {
				//v 是code  n 是name
				var _this = this;
				_this.code = v;
				_this.method(v, n);
			},
			//获得单个价格
			thisPrice(data) {
				var _this = this;				
				var newPrice = null;
				for(var i = 0; i < data.length; i++) {
					if(data[i].code == _this.code) {
						newPrice = data[i].closePrice
					}
				}
				_this.$emit('trans', newPrice); //要想父主件传的值	
			},
			//关掉推送执行函数
			offTime() {
				this.websocket.close();  //推送
			}

		},
		
		// 路由发生变化时
		beforeRouteLeave(to, from, next) {
			this.websocket.close();  //推送
			next();
		},
		watch: {
			'list': {
				handler: function(newValue, oldValue) {
					var _this = this;
//					_this.thisPrice(newValue);
				},
				deep: true,
			}
		},
		created() {
			this.getData();
			this.WebSocketindex();

		},
		mounted() {
			
		}
	}
</script>

<style>

</style>